<?php
/**
 * @package PWE.modele
 * @author Gmax <gmaxfr78@gmail.com>
 */
class modele_publication extends modele{
    protected static $_table = 'publication';
    protected $_discriminant = 'publication';
    public $type = 'publication';
    
    private $_id;
    private $_permalien;
    private $_date = '0000-00-00 00:00:00';
    private $_template;
    private $_statut_id = 1;
    private $_statut;
    private $_type_id = 1;
    private $_type;
    private $_post_id;
    private $_post = null;
    private $_category_id = 0;
    private $_category = null;
    private $_media_id;
    private $_media = null;
    private $_order_idx = 0;
    private $_is_deleted;

    function __construct($id=null){
        if($id!==null){
            $this->_id = $id;
            $this->_constructObject();
        }
    }
    
    private function _constructObject(){
        $sqlQuery = 'SELECT ';
        $sqlQuery .= 't.*, s.nom AS statut, ty.nom AS type ';
        $sqlQuery .= 'FROM '.self::getTable().' as t ';
        $sqlQuery .= 'LEFT JOIN '.PWE::getPrefixBdd().'statut AS s ON s.id = t.statut_id ';
        $sqlQuery .= 'LEFT JOIN '.PWE::getPrefixBdd().'type AS ty ON ty.id = t.type_id ';
        $sqlQuery .= 'WHERE t.id='.$this->_id.' ';
        $sqlQuery .= 'LIMIT 1';
        
        $datas = $this->_getOneResult($sqlQuery);
        if($datas){
            $this->_date = $datas['date'];
            $this->_template = $datas['template'];
            $this->_statut_id = $datas['statut_id'];
            $this->_statut = $datas['statut'];
            $this->_type_id = $datas['type_id'];
            $this->_type = $datas['type'];
            $this->_category_id = $datas['category_id']+0;
            $this->_post_id = $datas['post_id']+0;
            $this->_permalien = new modele_permalien($this->_discriminant,$this->_id);
            $this->_media_id = $datas['media_id']+0;
            $this->_order_idx = $datas['order_idx']+0;
            $this->_is_deleted = $datas['is_deleted'];
        }else{
            $this->_id = 0;
        }
    }
    public function getId(){
        return $this->_id;
    }
    public function setId($id=0){
        $this->_id = $id;
    }
    /**
     * renvoi la valeur numérique de $_is_deleted
     * @return int
     */
    public function getIsDeleted(){
        return $this->_is_deleted;
    }
    /**
     * indique si la publication marquée comme supprimé
     * @return boolean
     */
    public function isDeleted(){
        return ($this->_is_deleted==1)?true:false;
    }
    
    public function getDate(){
        return ($this->_date==='0000-00-00 00:00:00')?date("Y-m-d H:i:s"):$this->_date;
    }
    public function getDateCrea($input=false){
        return $this->getPost()->getDateCrea($input);
    }
    /**
     * 
     * @return \modele_post
     */
    public function getPost(){
        if($this->_post===null){
            $this->_post = ($this->_post_id>0)?new modele_post($this->_post_id):new modele_post();
        }
        return $this->_post;
    }
    /**
     * 
     * @return \modele_user|null
     */
    public function getUser(){
        return $this->getPost()->getUser();
    }
    public function getAuteur($input=false){
        $user = $this->getUser();
        return ($user!==null)?$user->getPrenom($input).' '.$user->getNom($input):'';
    }
    public function getAuteurLevel($input=false){
        return ($this->getUser()!==null)?$this->getUser()->getLevelNom($input):'';
    }
    public function getTitle($input=false){
        return $this->getPost()->getTitle($input);
    }
    /**
     * 
     * @param type $input
     * @return \modele_permalien
     */
    public function getPermalien(){
        if($this->_permalien === null) $this->_permalien = new modele_permalien($this->_discriminant);
        return $this->_permalien;
    }
    public function getUrl(){
        $urlCategory = ($this->getCategory()!==null)?$this->getCategory()->getUrl():PWE::getBaseURL();
        return $urlCategory.$this->getPermalien()->getLien();
    }
    public function getTranslatedUrl($lang=''){
        $urlCategory = ($this->getCategory()!==null)?$this->getCategory()->getTranslatedUrl($lang):PWE::getBaseURL();
        return $urlCategory.$this->getPermalien()->getTranslatedLien($lang);
    }
    public function getOrder(){
        return $this->_order_idx;
    }
    /**
     * enregistre un ordre pour les tri d'affichage
     * @param int $order
     */
    public function setOrder($order){
        if($order!=$this->_order_idx){
            $this->_order_idx = $order;
            $sql = 'UPDATE '.self::getTable().' SET order_idx='.$this->_order_idx.' WHERE id='.$this->getId();
            bdd_sql::doSql($sql);
        }
    }
    public function getContent($input=false){
        return $this->getPost()->getContent($input);
    }
    public function getSummary($input=false,$limit=2000){
        return $this->getPost()->getSummary($input,$limit);
    }
    /**
     * générer un résumé du contenu
     * @param string $string
     * @param int $limit
     */
    public function generateSummary(){
        return $this->getPost()->generateSummary($this->getContent());
    }
    public function getTypeId(){
        return $this->_type_id;
    }
    public function getType($input=false){
        if($input)return $this->inputFormat($this->_type);
        return $this->outputFormat($this->_type);
    }
    /**
     * 1=>brouillon
     * 2=>publié
     * @return int
     */
    public function getStatutId(){
        return $this->_statut_id;
    }
    public function getStatut($input=false){
        if($input)return $this->inputFormat($this->_statut);
        return $this->outputFormat($this->_statut);
    }
    public function getTitreSEO() {
        return $this->getPermalien()->getTitre();
    }
    public function getDescriptionSEO() {
        return $this->getPermalien()->getDescription();
    }
    /**
     * 
     * @return int
     */
    public function getCategoryId(){
        return $this->_category_id;
    }
    /**
     * renvoi la catégorie d'appartenance de l'article
     * @return \modele_category
     */
    public function getCategory(){
        if($this->_category===null){
            $this->_category = ($this->getCategoryId()>0)?new modele_category($this->getCategoryId()):new modele_category();
        }
        return $this->_category;
    }
    public function getTemplate(){
        if($this->_template !== null && $this->_template !== ''){
            return $this->_template;
        }else{
            return ($this->getCategory())?$this->getCategory()->getTemplate():PWE::getDefaultTemplate();
        }
    }
    public function getCustomVars($input=false){
        return $this->getPost()->getCustomVars($input);
    }
    public function getCustomVar($var,$input=false){
        $value = $this->getPost()->getCustomVar($var,$input);
        return $value;
    }
    public function setCustomVar($name,$value){
        return $this->getPost()->setCustomVar($name,$value);
    }
    /**
     * 
     * @return boolean
     */
    public function haveMedia(){
        return ($this->getMediaId()>0)?true:false;
    }
    /**
     * 
     * @return \modele_media
     */
    public function getMedia(){
        if($this->_media===null){
            if($this->_media_id>0) $this->_media = new modele_media($this->_media_id);
            else $this->_media = new modele_media();
        }
        return $this->_media;
    }
    public function getMediaId(){
        return ($this->_media_id>0)?$this->_media_id:'NULL';
    }
    public function addMedia($mediaId){
        $this->_media_id = $mediaId;
        $sqlQueryPublication = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryPublication .= 'media_id='.$mediaId.' ';
        $sqlQueryPublication .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryPublication,false);
        return true;
    }
    public function removeMedia($mediaId){
        $this->setDatas(array('_media_id'=>0));
        $sqlQueryPublication = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryPublication .= 'media_id=0 ';
        $sqlQueryPublication .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryPublication,false);
        return true;
    }
    
    /**
     * 
     * @param boolean $order
     * @return \modele_publication|null
     */
    public function getNextPublication($order=false){
        $sql = 'SELECT id FROM '.self::getTable().' ';
        $sql .= 'WHERE category_id='.$this->getCategoryId().' AND statut_id>1 AND is_deleted=0 AND id!='.$this->getId().' ';
        if($order){
            $sql .= 'AND order_idx>='.$this->getOrder().' ';
            $sql .= 'ORDER BY order_idx LIMIT 1';
        }else{
            $sql .= 'AND `date`>="'.$this->getDate().'" ';
            $sql .= 'ORDER BY `date` LIMIT 1';
        }
        $result = bdd_sql::doSql($sql,true);
        $sortie = null;
        if($result['count']==1){
            $sortie = new modele_publication($result['results'][0]['id']);
        }
        return $sortie;
    }
    
    /**
     * 
     * @param boolean $order
     * @return \modele_publication|null
     */
    public function getPreviousPublication($order=false){
        $sql = 'SELECT id FROM '.self::getTable().' ';
        $sql .= 'WHERE category_id='.$this->getCategoryId().' AND statut_id>1 AND is_deleted=0 AND id!='.$this->getId().' ';
        if($order){
            $sql .= 'AND order_idx<='.$this->getOrder().' ';
            $sql .= 'ORDER BY order_idx DESC LIMIT 1';
        }else{
            $sql .= 'AND `date`<="'.$this->getDate().'" ';
            $sql .= 'ORDER BY `date` DESC LIMIT 1';
        }
        $result = bdd_sql::doSql($sql,true);
        $sortie = null;
        if($result['count']==1){
            $sortie = new modele_publication($result['results'][0]['id']);
        }
        return $sortie;
    }
    
    public function getDatas($input=false){
        $datas = array(
            'id'=>$this->getId(),
            'auteur'=>$this->getAuteur($input),
            'date'=>$this->getDate($input),
            'media'=>$this->getMedia(),
            'template'=>$this->getTemplate(),
            'date_crea'=>$this->getDateCrea($input),
            'title'=>$this->getTitle($input),
            'titre_seo'=>$this->getPermalien()->getTitre($input),
            'description_seo'=>$this->getPermalien()->getDescription($input),
            'permalien'=>$this->getPermalien()->getLien(),
            'url'=>$this->getUrl(),
            'custom_vars'=>$this->getCustomVars($input),
            'content'=>$this->getContent($input),
            'summary'=>$this->getSummary($input),
            'statut'=>$this->getStatut($input),
            'category_id'=>$this->getCategoryId(),
            'statut_id'=>$this->getStatutId(),
            'type_id'=>$this->getTypeId(),
            'type'=>$this->getType(),
            'modele'=>'publication',
            'order_idx'=>$this->getOrder(),
            'is_deleted'=>$this->isDeleted()
        );
        
        return $datas;
    }
    public function setDatas($datas){
        foreach($datas as $k=>$v){
            if(substr($k, 0, 1) !== '_') $k = '_'.$k;
            if($k != '_id' && property_exists('modele_publication',$k)){
                $this->$k = $v;
            }
        }
        $this->getPost()->setDatas($datas);
        $this->getPermalien()->setDatas($datas);
        return true;
    }
    public function save(){
        //post
        $this->getPost()->save();
        $postId = $this->getPost()->getId();
        if($postId>0){
           //publication
           $sqlQuery = 'INSERT INTO '.self::getTable().' ';
           $sqlQuery .= '(date,statut_id,post_id,category_id,type_id,template,order_idx) ';
           $sqlQuery .= 'VALUES ("'.$this->getDate().'",'.$this->getStatutId().','.$postId.','.$this->getCategory()->getId().','.$this->getTypeId().',"'.$this->getTemplate().'",'.$this->getOrder().')';
           bdd_sql::doSql($sqlQuery,false);
           
           $this->setId(bdd_sql::getLastInsertId());

           if($this->getId()>0){
               //permalien
               $this->getPermalien()->setDatas(array('_modele_id'=>$this->getId()));
               $this->getPermalien()->save();

               return array('success'=>true,'datas'=>$this->getDatas());
           }else{
               return array('success'=>false,'datas'=>array());
           }
        }else{
            return array('success'=>false,'datas'=>array());
        }
    }
    public function update(){
        //post
        $this->getPost()->update();
        //publication
        $sqlQueryPublication = 'UPDATE '.self::getTable().' SET ';
        $sqlQueryPublication .= 'date="'.$this->getDate().'",';
        $sqlQueryPublication .= 'category_id='.$this->getCategoryId().', ';
        $sqlQueryPublication .= 'type_id='.$this->getTypeId().', ';
        $sqlQueryPublication .= 'statut_id='.$this->getStatutId().', ';
        $sqlQueryPublication .= 'media_id='.$this->getMediaId().', ';
        $sqlQueryPublication .= 'order_idx='.$this->getOrder().', ';
        $sqlQueryPublication .= 'is_deleted='.$this->getIsDeleted().', ';
        $sqlQueryPublication .= 'template="'.$this->getTemplate().'" ';
        $sqlQueryPublication .= 'WHERE id='.$this->getId().' LIMIT 1';
        bdd_sql::doSql($sqlQueryPublication,false);

        //permalien
        $this->getPermalien()->update();

        return array('success'=>true,'datas'=>$this->getDatas());
    }
    
    public function delete() {
        $this->getPermalien()->delete();
        $sqlDelete = 'DELETE FROM '.self::getTable().' WHERE id='.$this->getId();
        bdd_sql::doSql($sqlDelete,false);
        $this->getPost()->delete();
        return array('success'=>true,'datas'=>array());
    }
    /* methodes statiques */
    /**
     * 
     * @return string
     */
    public static function getTable(){
        return PWE::getPrefixBdd().self::$_table;
    }
    
    /**
     * 
     * @param int $start
     * @param int $type_id
     * @return array \modele_publication
     */
    public static function getListe($start = 0,$type_id = 1){
        $sqlQuery = 'SELECT p.id AS id FROM '.self::getTable().' AS p LEFT JOIN '.modele_category::getTable().' AS c ON c.id=p.category_id WHERE p.is_deleted=0 AND p.type_id='.$type_id.' AND c.discriminant!="page" ORDER BY p.category_id, p.date DESC';
        if($start>0){
            $sqlQuery .= ''; // TODO pagination
        }
        $retour = array();
        $results = bdd_sql::doSql($sqlQuery,true);
        if($results['count']>0){
            foreach($results['results'] as $publicationData ){
                $retour[] = new modele_publication($publicationData['id']);
            }
        }
        return $retour;
    }
    /**
     * renvoi la liste des article de la catégorie
     * @param mixed $category
     * @param int $start
     * @param int $limit
     * @param boolean $is_public
     * @return \modele_publication
     */
    public static function getListeFromCategory($category,$start = 0,$limit = 0,$is_public=0){
        if(is_int($category)){
            $category_id = $category;
        }else{
            $aCategory = navigation::findCategoryByPermalien($category);
            if($aCategory['success']){
                $category_id = $aCategory['modele_id'];
            }
        }
        $retour = array();
        
        if($category_id>0){
            $sqlQuery = 'SELECT p.id AS id FROM '.self::getTable().' AS p WHERE is_deleted=0 AND p.category_id='.$category_id;
            if($is_public===1){
                $sqlQuery .= ' AND p.statut_id=2';
            }
            $sqlQuery .= ' ORDER BY  p.order_idx, p.date DESC';
            if($limit>0){
                $sqlQuery .=  ' LIMIT '.$start.', '.$limit;
            }
            
            $results = bdd_sql::doSql($sqlQuery,true);
            if($results['count']>0){
                foreach($results['results'] as $publicationData ){
                    $retour[] = new modele_publication($publicationData['id']);
                }
            }
        }
        return $retour;
    }
}
?>